<template>
  <view class="home-container">
    <!-- 主页内容 -->
    <view class="home-content">
      <text>主页</text>
    </view>

    <!-- 健康数据表单 -->
    <view class="health-form">
      <view class="form-item">
        <text class="label">身高 (cm)</text>
        <text class="value">{{ height || '未记录' }}</text>
      </view>
      <view class="form-item">
        <text class="label">体重 (kg)</text>
        <text class="value">{{ weight || '未记录' }}</text>
      </view>
      <view class="form-item">
        <text class="label">BMI</text>
        <text class="value">{{ bmi || '未记录' }}</text>
      </view>
    </view>

    <!-- 健康数据按钮 -->
    <button class="health-btn" @click="openHealthModal">记录健康数据</button>

    <!-- 健康数据模态框 -->
    <view class="modal-overlay" v-if="isHealthModalVisible" @click="closeHealthModal">
      <view class="health-modal" @click.stop>
        <!-- 健康数据页面内容 -->
        <HealthDataPage @close="closeHealthModal" @submit="handleSubmit" />
      </view>
    </view>

    <!-- 食谱列表 -->
    <scroll-view class="recipe-list" scroll-y>
      <view v-for="recipe in recipes" :key="recipe.recipe_id" class="recipe-item">
        <text class="dish-name">{{ recipe.dish_name }}</text>
        <view class="ingredients" v-html="renderMarkdown(recipe.ingredients)"></view>
        <view class="instructions" v-html="renderMarkdown(recipe.instructions)"></view>
      </view>
    </scroll-view>

    <!-- 食谱操作按钮 -->
    <view class="recipe-actions">
      <button @click="openAddModal" class="action-btn">添加</button>
      <button @click="openEditModal" class="action-btn">修改</button>
      <button @click="deleteSelectedRecipe" class="action-btn delete-btn">删除</button>
    </view>

    <!-- 添加食谱模态框 -->
    <view class="modal-overlay" v-if="isAddModalVisible" @click="closeAddModal">
      <view class="recipe-modal" @click.stop>
        <input v-model="newRecipe.dish_name" placeholder="菜品名称" class="input" />
        <textarea v-model="newRecipe.ingredients" placeholder="食材（Markdown 格式）" class="textarea"></textarea>
        <textarea v-model="newRecipe.instructions" placeholder="做法（Markdown 格式）" class="textarea"></textarea>
        <button @click="addRecipe" class="add-btn">提交</button>
      </view>
    </view>

    <!-- 修改食谱模态框 -->
    <view class="modal-overlay" v-if="isEditModalVisible" @click="closeEditModal">
      <view class="recipe-modal" @click.stop>
        <input v-model="editRecipe.dish_name" placeholder="菜品名称" class="input" />
        <textarea v-model="editRecipe.ingredients" placeholder="食材（Markdown 格式）" class="textarea"></textarea>
        <textarea v-model="editRecipe.instructions" placeholder="做法（Markdown 格式）" class="textarea"></textarea>
        <button @click="updateRecipe" class="add-btn">提交</button>
      </view>
    </view>
  </view>
</template>

<script>
import HealthDataPage from './user_center/HealthDataPage.vue'; // 引入健康数据页面组件
import axios from 'axios';
// import marked from 'marked';
import { marked } from 'marked';
//版本问题
import DOMPurify from 'dompurify'; // 用于净化 HTML，防止 XSS 攻击

export default {
  components: {
    HealthDataPage
  },
  data() {
    return {
      height: null, // 身高
      weight: null, // 体重
      bmi: null, // BMI
      isHealthModalVisible: false, // 控制健康数据模态框显示
      recipes: [], // 食谱列表
      newRecipe: {
        dish_name: '',
        ingredients: '',
        instructions: ''
      },
      editRecipe: {
        recipe_id: null,
        dish_name: '',
        ingredients: '',
        instructions: ''
      },
      isAddModalVisible: false, // 控制添加食谱模态框显示
      isEditModalVisible: false, // 控制修改食谱模态框显示
      selectedRecipeId: null // 当前选中的食谱 ID
    };
  },
  methods: {
    // 打开健康数据模态框
    openHealthModal() {
      this.isHealthModalVisible = true;
    },
    // 关闭健康数据模态框
    closeHealthModal() {
      this.isHealthModalVisible = false;
    },
    // 处理健康数据表单提交
    handleSubmit(data) {
      this.height = data.height;
      this.weight = data.weight;
      this.calculateBMI(); // 计算 BMI
    },
    // 计算 BMI
    calculateBMI() {
      if (this.height && this.weight) {
        const heightInMeters = this.height / 100; // 将身高从厘米转换为米
        this.bmi = (this.weight / (heightInMeters * heightInMeters)).toFixed(2); // 计算 BMI 并保留两位小数
      } else {
        this.bmi = null;
      }
    },
    // 渲染 Markdown 文本
    renderMarkdown(markdown) {
      return DOMPurify.sanitize(marked(markdown)); // 净化 HTML
    },
    // 获取用户食谱列表
    async fetchRecipes() {
      try {
        const response = await axios.get(`${this.$baseUrl}/recipe_work/recipes`, {
          headers: {
            Authorization: 'Bearer ' + uni.getStorageSync('access_token') // 携带 Token
          }
        });

        if (response.status === 200) {
          this.recipes = response.data.recipes;
        } else {
          throw new Error('获取食谱失败');
        }
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' });
      }
    },
    // 打开添加食谱模态框
    openAddModal() {
      this.isAddModalVisible = true;
    },
    // 关闭添加食谱模态框
    closeAddModal() {
      this.isAddModalVisible = false;
      this.newRecipe = { dish_name: '', ingredients: '', instructions: '' }; // 清空表单
    },
    // 添加食谱
    async addRecipe() {
      if (!this.newRecipe.dish_name || !this.newRecipe.ingredients || !this.newRecipe.instructions) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }

      try {
        const response = await axios.post(`${this.$baseUrl}/recipe_work/recipes`, this.newRecipe, {
          headers: {
            Authorization: 'Bearer ' + uni.getStorageSync('access_token') // 携带 Token
          }
        });

        if (response.status === 200) {
          uni.showToast({ title: '食谱添加成功', icon: 'success' });
          this.closeAddModal(); // 关闭模态框
          await this.fetchRecipes(); // 重新获取食谱列表
        } else {
          throw new Error('添加食谱失败');
        }
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' });
      }
    },
    // 打开修改食谱模态框
    openEditModal() {
      const selectedRecipe = this.recipes.find(recipe => recipe.recipe_id === this.selectedRecipeId);
      if (selectedRecipe) {
        this.editRecipe = { ...selectedRecipe };
        this.isEditModalVisible = true;
      } else {
        uni.showToast({ title: '请先选择一个食谱', icon: 'none' });
      }
    },
    // 关闭修改食谱模态框
    closeEditModal() {
      this.isEditModalVisible = false;
      this.editRecipe = { recipe_id: null, dish_name: '', ingredients: '', instructions: '' }; // 清空表单
    },
    // 修改食谱
    async updateRecipe() {
      try {
        const response = await axios.put(`${this.$baseUrl}/recipe_work/recipes/${this.editRecipe.recipe_id}`, this.editRecipe, {
          headers: {
            Authorization: 'Bearer ' + uni.getStorageSync('access_token') // 携带 Token
          }
        });

        if (response.status === 200) {
          uni.showToast({ title: '食谱修改成功', icon: 'success' });
          this.closeEditModal(); // 关闭模态框
          await this.fetchRecipes(); // 重新获取食谱列表
        } else {
          throw new Error('修改食谱失败');
        }
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' });
      }
    },
    // 删除选中的食谱
    async deleteSelectedRecipe() {
      if (!this.selectedRecipeId) {
        uni.showToast({ title: '请先选择一个食谱', icon: 'none' });
        return;
      }

      try {
        const response = await axios.delete(`${this.$baseUrl}/recipe_work/recipes/${this.selectedRecipeId}`, {
          headers: {
            Authorization: 'Bearer ' + uni.getStorageSync('access_token') // 携带 Token
          }
        });

        if (response.status === 200) {
          uni.showToast({ title: '食谱删除成功', icon: 'success' });
          this.selectedRecipeId = null; // 清空选中状态
          await this.fetchRecipes(); // 重新获取食谱列表
        } else {
          throw new Error('删除食谱失败');
        }
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' });
      }
    }
  },
  async mounted() {
    // 页面加载时获取健康数据（假设从后端接口获取）
    // 这里可以调用 API 获取用户的身高和体重数据
    // 例如：
    // const response = await this.fetchHealthData();
    // this.height = response.height;
    // this.weight = response.weight;
    // this.calculateBMI();

    // 获取食谱列表
    await this.fetchRecipes();
  }
};
</script>

<style>
.home-container {
  padding: 20px;
  background-color: #F2F6F4; /* 温暖的背景色 */
  color: #333333;
  font-family: 'Arial', sans-serif; /* 清新的字体 */
}

.home-content {
  margin-bottom: 20px;
}

.health-form {
  background: #FFFFFF;
  padding: 20px;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.label {
  font-size: 16px;
  color: #4D5B5B; /* 深绿色文本 */
}

.value {
  font-size: 16px;
  color: #333333;
  font-weight: bold;
}

.health-btn {
  background: #A7C6A6; /* 清新的绿色按钮 */
  color: #FFFFFF;
  border: none;
  border-radius: 10px;
  padding: 12px;
  font-size: 18px;
  cursor: pointer;
  width: 100%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.health-btn:hover {
  background: #8DAF8E; /* 鼠标悬停时的色调 */
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5); /* 半透明遮罩 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.health-modal,
.recipe-modal {
  background: #FFFFFF;
  padding: 20px;
  border-radius: 15px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.recipe-list {
  height: 300px; /* 设置固定高度 */
  margin-top: 20px;
  overflow-y: auto;
}

.recipe-item {
  background: #FFFFFF;
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.dish-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.ingredients,
.instructions {
  font-size: 16px;
  margin-top: 10px;
}

.recipe-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.action-btn {
  background: #A7C6A6; /* 清新的绿色按钮 */
  color: #FFFFFF;
  border: none;
  border-radius: 10px;
  padding: 12px;
  font-size: 18px;
  cursor: pointer;
  flex: 1;
  margin: 0 5px;
}

.action-btn.delete-btn {
  background: #FF6B6B; /* 红色删除按钮 */
}

.action-btn:hover {
  opacity: 0.9;
}

.input,
.textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #A7C6A6; /* 清新的绿色边框 */
  border-radius: 10px;
  font-size: 16px;
  margin-bottom: 10px;
}

.textarea {
  height: 100px;
}

.add-btn {
  background: #A7C6A6; /* 清新的绿色按钮 */
  color: #FFFFFF;
  border: none;
  border-radius: 10px;
  padding: 12px;
  font-size: 18px;
  cursor: pointer;
  width: 100%;
}

.add-btn:hover {
  background: #8DAF8E; /* 鼠标悬停时的色调 */
}
</style>